<?php

namespace App\Services\Assess;

use App\Models\Account\UserAccountModel;
use App\Models\Assess\AutoEmailModel;
use App\Models\Assess\AutoEmailSkuModel;
use App\Models\Assess\EmailTemplateModel;
use App\Services\BaseService;
use App\Services\Common\CommonService;
use App\Services\Common\RedisService;
use Illuminate\Support\Facades\Log;

class AutoEmailService extends BaseService
{

    public $intervalTime = [
        ['label' => '0分钟', 'val' => 0],
        ['label' => '5分钟', 'val' => 5],
        ['label' => '10分钟', 'val' => 10],
        ['label' => '30分钟', 'val' => 30],
        ['label' => '1个小时', 'val' => 60],
        ['label' => '2个小时', 'val' => 120],
        ['label' => '4个小时', 'val' => 240],
        ['label' => '6个小时', 'val' => 360],
        ['label' => '1天', 'val' => 1440]
    ];

    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = new AutoEmailModel();
    }

    /**
     * @Notes:获取自动信配置
     * @Interface getAutoEmailConfig
     * @return array
     * @author: wuyu
     * @Time: 2023/6/25   14:49
     */
    public function getAutoEmailConfig()
    {
        $config = [];
        //获取当前用户创建的邮件模板
        $EmailTemplateModel = new EmailTemplateModel();

        if (!in_array($EmailTemplateModel->userId,$EmailTemplateModel->userAllIds)){
            $config['email_template_list'] = $EmailTemplateModel->where('create_user','=',$EmailTemplateModel->userId)->get(['id','name'])->toArray();
        }else{
            $config['email_template_list'] = $EmailTemplateModel->get(['id','name'])->toArray();
        }
        //间隔多久发送自动信
        $config['interval_time_list'] = $this->intervalTime;
        //获取用户
        $config['user_list'] = RedisService::getUserList();

        return message("操作成功", true, $config);
    }

    /**
     * @Notes:获取数据列表
     * @Interface getList
     * @return array
     * @author: wuyu
     * @Time: 2023/6/25   15:12
     */
    public function getList()
    {
        $param = request()->all();
        // 查询条件
        $map[] = ['mark','=',1];
        $name = getter($param, 'name', '');
        $createUser = getter($param, 'create_user', '');
        $sku = getter($param, "sku",'');
        $sort = getter($param, 'sort', 'create_time');
        $order = getter($param, 'order', 'desc');
        $page_size = getter($param, 'page', 1);
        $limit = getter($param, 'limit', 10);

        $skuStr = str_replace(['；', ',', '，',"\r\n", "\r", "\n"], ';', $sku);
        if (!empty($skuStr)) $skuArr = array_unique(explode(';', $skuStr));

        if (!empty($createUser)) $map[] = ['m.create_user', '=', $createUser];

        //权限过滤 组员可以看一个组的信息
//        $createUserList = CommonService::userAuth();
        $skuAuthList = CommonService::skuAuth();

        $offset = ($page_size - 1) * $limit;
        $mainTable = $this->model->getTable();
        $AutoEmailSkuModel = new AutoEmailSkuModel();
        $sonTable = $AutoEmailSkuModel->getTable();
        $model = $this->model::from("$mainTable as m")
            ->select('m.*')
            ->leftJoin("$sonTable as s", 's.auto_email_id', '=', 'm.id')
            ->distinct(true)
            ->where($map);
        $model2 = $this->model::from("$mainTable as m")
            ->select('m.id')
            ->leftJoin("$sonTable as s", 'm.id', '=', 's.auto_email_id')
            ->distinct('m.id')
            ->where($map);
        if (!empty($skuArr)){
            $model->whereIn('s.sku',$skuArr);
            $model2->whereIn('s.sku',$skuArr);
        }
        if (!empty($skuAuthList) && empty($skuArr)){
            $model->whereIn('s.sku',$skuAuthList);
            $model2->whereIn('s.sku',$skuAuthList);
        }

        $list = $model
            ->orderBy($sort, $order)
            ->offset($offset)
            ->limit(PERPAGE)
            ->get()->toArray();
        $count = $model2->count();

        $emailTemplateCol = [];
        $skuArr2 = [];
        if (!empty($list)){
            //获取当前用户创建的邮件模板
            $templateId = array_column($list,'template_id');
            $EmailTemplateModel = new EmailTemplateModel();
            $emailModel = $EmailTemplateModel->where('mark','=',1)->whereIn('id',$templateId);
            if (!empty($name)) $emailModel->where('name','like',"%{$name}%");
            $emailTemplateList = $emailModel->get(['id','name'])->toArray();
            $emailTemplateCol = array_column($emailTemplateList,'name','id');

            $AutoEmailSkuModel = new AutoEmailSkuModel();
            $ids = array_column($list,'id');
            $skuList = $AutoEmailSkuModel->whereIn('auto_email_id',$ids)->get()->toArray();
            foreach ($skuList as $val){
                $skuArr2[$val['auto_email_id']][] = $val['sku'];
            }
        }

        //获取定时时间
        $intervalTimeCol = array_column($this->intervalTime,'label','val');

        foreach ($list as $key => $val) {
            $info = $this->model->getInfo($val['id']);
            if (!$info) {
                continue;
            }
            $val['template_name'] = $emailTemplateCol[$val['template_id']] ?? '';
            $val['interval_time_name'] = $intervalTimeCol[$val['interval_time']] ?? '';
            if (!empty($skuArr2[$val['id']])){
                $val['sku_list'] = implode(';',$skuArr2[$val['id']]);
            }
            $val = array_merge($val,$info);
            $list[$key] = $val;
        }
        return array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $list,
            "count" => $count,
        );

    }


    /**
     * @Notes:新增或修改
     * @Interface edit
     * @return array
     * @author: wuyu
     * @Time: 2023/6/25   14:48
     */
    public function edit()
    {
        try {
            $params = request()->all();
            $id = $params['id'] ?? 0;
            $templateId = $params['template_id'] ?? 0;
            $intervalTime = $params['interval_time'] ?? 0;
            $skuList = $params['sku_list'] ?? '';
            $emailName = $params['email_name'] ?? '';
            $userId = $this->model->userId;

            if (empty($skuList)) throw new \Exception('sku不能为空');
            if (empty($templateId)) throw new \Exception('邮件模板不能为空');
            if (empty($userId)) throw new \Exception('用户不能为空');
            if (empty($emailName)) throw new \Exception('接收邮箱不能为空');

            $skuList = str_replace(['；', ',', '，',"\r\n", "\r", "\n"], ';', $skuList);
            $skuArr = array_unique(explode(';',$skuList));
            $exists = $this->model->getOne([
                ['template_id', '=', $templateId],
                ['create_user', '=', $userId],
            ]);
            if (!empty($exists) && empty($id)) {
                throw new \Exception('当前用户,自动信已存在,请勿重复添加');
            } elseif (!empty($exists) && $exists['id'] != $id) {
                throw new \Exception('当前用户,自动信已存在,请勿重复添加');
            }

            $data = [
                'template_id'=>$templateId,
                'interval_time'=>$intervalTime,
                'email_name'=>$emailName
            ];

            if (empty($id)) {
                $data['create_user'] = $userId;
                $data['update_time'] = time();
                $data['create_time'] = time();
                $insertId = $this->model->insertGetId($data);
            } else {
                $data['update_user'] = $userId;
                $data['update_time'] = time();
                $insertId = $id;
                $this->model->where('id', '=', $id)->update($data);
                $this->model->cacheReset($id, $data, $id);
            }
            if (empty($insertId)) throw new \Exception('操作失败');

            $AutoEmailSkuModel = new AutoEmailSkuModel();
            $AutoEmailSkuModel->where('auto_email_id','=',$insertId)->delete();
            foreach ($skuArr as $sku){
                $skuData = [
                    'auto_email_id'=>$insertId,
                    'sku'=>$sku
                ];
                $AutoEmailSkuModel->insert($skuData);
            }

            return message("保存成功", true, []);

        } catch (\Exception $e) {
            return message("保存失败:" . $e->getMessage(), false, []);
        }
    }


    public function status()
    {

        $params = request()->all();

        $id = $params['id'] ?? 0;
        $status = $params['status'] ?? 0;
        if (empty($id) || empty($status)) {
            return message("参数不存在", false, []);
        }
        $data = ['status' => $status];
        $this->model->where('id', $id)->update($data);
        $this->model->cacheReset($id, $data, $id);
        return message("操作成功", true, []);
    }


}
